<template>
  <div class="login">
    <div class="login-content">
      <div class="login-form login-item">
        <p class="login-title">{{ title }}</p>
        <el-form :model="userInfo" :rules="rule" ref="ruleForm" label-width="70px">
          <el-form-item label="用户名" prop="name">
            <el-input v-model="userInfo.userName"></el-input>
          </el-form-item>
          <el-form-item label="密  码" prop="password">
            <el-input v-model="userInfo.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click.prevent="submitForm(ruleForm)">登 录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, markRaw } from 'vue'
import { useRouter } from "vue-router";
import axios from "@/api";
import { InitIcon } from "@/common";
import { loginUrl } from '../../api/index';
import store from "@/store/index";
import { ElMessage, ElMessageBox } from 'element-plus'

const title = ref('登录');
const router = useRouter();
const userInfo = reactive({
  userName: "",
  password: ""
});
const rule = reactive({
  user: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    }
  ]
});

const myAxios = axios.create({
  baseURL: loginUrl() + "api/",
})

const ruleForm = ref();
const submitForm = (formEl) => {
  formEl.validate(async valid => {
    if (valid) {
      //调用Api
      let url = `Account`;
      let { data } = await myAxios.post(url, userInfo);
      let { data: d, success, message, otherSource } = data;
      if (success) {
        //保存Token
        store().$patch({
          accessToken: otherSource.accessToken,
          refreshToken: otherSource.refreshToken,
          accountInfo: d
        });

        await userMenus();
        
        //跳转
        router.push("/home");
      } else {
        ElMessage({
          type: 'error',
          message: message,
          icon: markRaw(InitIcon('Warning'))
        })
      }
    }
  });
}

const userMenus = async () => {
  let { data } = await axios.get("/Menu/GetButtonByCurrentUser");
  let { data: d, success, message } = data;

  if (!success) {
    ElMessage({
      type: 'error',
      message: message,
      icon: markRaw(InitIcon('Warning'))
    });
  }

  if (d.length === 0) {
    return;
  }

  store().$patch({
    buttons: d
  });
}
</script>